package com.educhains.web.interceptor;

import com.educhains.module.user.service.UserService;
import com.educhains.module.user.vo.User;
import com.educhains.web.util.AESUtils;
import com.educhains.web.util.SessionUtils;
import com.educhains.web.util.StringUtils;
import com.educhains.web.util.WebUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author YuRun
 * @since 2017年8月26日
 */
public class AutoLoginControlInterceptor implements HandlerInterceptor {

    @Autowired
    UserService userService = null;

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object object) throws Exception {
        User sessionUser = SessionUtils.getUser(request);
        if (sessionUser == null) {
            String loginCookieUserEmail = "";
            String loginCookiePassword = "";
            Cookie[] cookies = request.getCookies();
            if (cookies == null) {
                return true;
            }
            for (Cookie cookie : cookies) {
                if (User.USER_EMAIL_COOKIE_KEY.equals(cookie.getName())) {
                    loginCookieUserEmail = cookie.getValue();
                } else if (User.USER_PASSWORD_COOKIE_KEY.equals(cookie.getName())) {
                    loginCookiePassword = cookie.getValue();
                }
            }
            if (StringUtils.isEmpty(loginCookieUserEmail) || StringUtils.isEmpty(loginCookiePassword)) {
                return true;
            }

            User dbUser = userService.getUserByEmail(loginCookieUserEmail);
            if (dbUser == null) {
                return true;
            }
            //FIXME
            if (loginCookiePassword.compareTo(dbUser.getUserPwd()) == 0) {
                request.getSession().setAttribute(User.USER_SESSION_KEY, dbUser);
            }
        }
        return true;
    }

    public void postHandle(HttpServletRequest arg0, HttpServletResponse response, Object object, ModelAndView modelAndView) throws Exception {

    }

    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object object, Exception exception)
            throws Exception {
    }
}
